<template>
  <div class="image-loader-container">
    <img v-if="!done" :src="placeholder" class="placeholder" />
    <img
      :src="src"
      class="origin"
      :style="{
        opacity: originOpacity,
        transition: `${duration}ms`,
      }"
      @load="handleLoad"
    />
  </div>
</template>

<script>
export default {
  name: "ImageLoader",
  props: {
    // 原始图片的路径
    src: {
      type: String,
      required: true,
    },
    // 占位图片的路径
    placeholder: {
      type: String,
      required: true,
    },
    // 事件间隔
    duration: {
      type: Number,
      default: 500,
    },
  },
  data() {
    return {
      originLoad: false, // 原图是否加载完成
      done: false,
    };
  },
  computed: {
    // 原始图片的透明度，如果加载完了，透明度为1
    originOpacity() {
      return this.originLoad ? 1 : 0;
    },
  },
  methods: {
    handleLoad(ev) {
      this.originLoad = true;
      setTimeout(() => {
        this.done = true;
        this.$emit("load");
      }, this.duration);
    },
  },
};
</script>

<style lang="less" scoped>
@import "~@/styles/mixin.less";

.image-loader-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;

  img {
    .self-fill();
    object-fit: cover;
  }

  .origin {
    opacity: 0;
  }

  .placeholder {
    filter: blur(1vw);
  }
}
</style>